package zookeeper;

import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by luoqifei on 2016/9/7.
 */
public class ZkService {
    public static final Logger log = LoggerFactory.getLogger(ZkService.class);
    private ZooKeeper zooKeeper;
    private String zkUrl = "";
    private int timeout = 5000;
    public ZkService(){
    }
    public ZkService(String connectString){
        this.zkUrl = connectString;
        try {
            start();
        } catch (IOException e) {
            log.error("Error happen when start zookeeper service.");
            e.printStackTrace();
        }
    }

    private void start() throws IOException {
        zooKeeper = new ZooKeeper(this.zkUrl, timeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("Hello,boy,I am zookeeper service ,I am ready now.....");
            }
        });
    }
    public void close() throws InterruptedException {
        if(zooKeeper !=  null ){
            zooKeeper.close();
        }
    }
    public void create(String path, String data){
        try {
            // // 子节点的类型设置为EPHEMERAL_SEQUENTIAL, 表明这是一个临时节点, 且在子节点的名称后面加上一串数字后缀
            String createPath = zooKeeper.create(path,data.getBytes("utf-8"),
                    ZooDefs.Ids.CREATOR_ALL_ACL,CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println("create: " + createPath);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}
